package com.jeect.config;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

@Component
public class MyZuulFilter extends ZuulFilter {
    @Autowired
    private HttpServletRequest request;
    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        System.out.println("id===="+request.getSession().getAttribute("id"));
        RequestContext context = RequestContext.getCurrentContext();

        Enumeration<String> headers = request.getHeaderNames();
        while (headers.hasMoreElements()) {
            String name = headers.nextElement();
            System.out.println(name + ":" + request.getHeader(name));
        }

        Cookie[] cookies = request.getCookies();
        String session ="";
        if(cookies!=null && cookies.length>0) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equalsIgnoreCase("session")) {
                    session = cookie.getValue();
                }
                System.out.println(cookie.getName() + ":" + cookie.getValue());
            }
            context.addZuulRequestHeader("Cookie", "SESSION=" + session);
        }
        context.setRequest(request);
        context.setSendZuulResponse(true);// 对该请求进行路由
        context.setResponseStatusCode(200);
        context.set("isSuccess", true);// 设值，让下一个Filter看到上一个Filter的状态

//        context.setSendZuulResponse(true);
//        context.setResponseStatusCode(HttpStatus.ACCEPTED.value());
        return null;
    }

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }
}
